package org.feng.navigation.rest.gatewayimpl.tianxing;

import lombok.extern.slf4j.Slf4j;
import org.feng.navigation.common.util.GsonUtil;
import org.feng.navigation.domain.rpc.tianxing.domainobject.BaseTianXingRequest;
import org.feng.navigation.domain.rpc.tianxing.domainobject.BaseTianXingResponse;
import org.feng.navigation.domain.rpc.tianxing.gateway.TianXingHttpClient;
import org.feng.navigation.rest.config.AppInfoConfig;
import org.feng.navigation.rest.config.HttpUrlConfig;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 天行HttpClient实现
 *
 * @version v1.0
 * @author: junzi
 * @date: 2023年02月05日 13时49分
 */
@Slf4j
@Component
public class TianXingHttpClientImpl implements TianXingHttpClient {
    @Resource
    private AppInfoConfig appInfoConfig;
    @Resource
    private HttpUrlConfig httpUrlConfig;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private TianXingConvert tianXingConvert;

    @Override
    public <R extends BaseTianXingResponse> R execute(BaseTianXingRequest<R> request) {
        String appKey = appInfoConfig.getTianXing().getAppKey();
        String url = httpUrlConfig.getTianXing();
        // 设置天行数据的key
        request.setKey(appKey);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setAcceptCharset(List.of(StandardCharsets.UTF_8));

        // 转换请求参数
        MultiValueMap<String, Object> paramsMap = tianXingConvert.convertRequest(request);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramsMap, headers);
        log.info("天行数据接口{}请求参数：{}", request.getPath(), paramsMap);
        R response;
        try {
            String responseString = restTemplate.postForObject(url + request.getPath(), httpEntity, String.class);
            log.info("天行数据接口{}调用成功：{}", request.getPath(), responseString);
            response = GsonUtil.fromJson(responseString, request.getResponseClass());
        } catch (Exception e) {
            log.error("天行数据接口{}调用失败：{}", request.getPath(), e.getMessage());
            try {
                response = request.getResponseClass().getConstructor().newInstance();
                response.setCode(-1);
                response.setMsg("天行数据接口调用失败:" + e.getMessage());
            } catch (InstantiationException | IllegalAccessException | NoSuchMethodException |
                     InvocationTargetException ex) {
                throw new RuntimeException(ex);
            }
        }
        return response;
    }
}
